<template>
  <div class="history-page">
    <h2>推荐题目反馈历史</h2>

    <div class="filters">
      <label>排序：</label>
      <select v-model="sortOrder" @change="applyFilters">
        <option value="desc">时间戳降序</option>
        <option value="asc">时间戳升序</option>
      </select>

      <label>状态筛选：</label>
      <select id="statusSelect" v-model="selectedStatus" multiple @change="applyFilters" @click="handleClick">
        <option v-for="status in statusOptions" :key="status.value" :value="status.value">
          {{ status.text }}
        </option>
      </select>
    </div>

    <table>
      <thead>
        <tr>
          <th>题目</th>
          <th>反馈状态</th>
          <th>时间戳</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in filteredHistory" :key="item.id">
          <td>
            <a 
              :href="getProblemLink(item.problem.problem_number)" 
              target="_blank" 
              class="problem-link"
              @mouseenter="handleMouseEnter(index, item.problem)" 
              @mouseleave="hideTooltip"
            >
              {{ item.problem.problem_number }}: {{ item.problem.problem_name }}
            </a>
            <div v-if="hoveredIndex === index" class="problem-tooltip">
              <p>难度：{{ item.problem.difficulty }}</p>
              <p>标签：</p>
              <div class="tags">
                <span v-for="tag in item.problem.tags" :key="tag.index" class="tag">
                  {{ tag.tag_name }}
                </span>
              </div>
            </div>
          </td>
          <td>{{ item.status }}</td>
          <td>{{ formatTimestamp(item.timestamp) }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from '@/axios';

export default {
  name: 'RecommendationHistory',
  data() {
    return {
      history: [],
      sortOrder: 'desc',
      selectedStatus: [],
      historyStatus: [],
      hoveredIndex: null,
      hoveredProblem: null,
      statusOptions: [
        { value: 'AC', text: 'Accepted' },
        { value: 'WA', text: 'Wrong Answer' },
        { value: 'TLE', text: 'Time Limit Exceeded' },
        { value: 'SKIP', text: 'Skipped' },
        { value: 'MLE', text: 'Memory Limit Exceeded' },
        { value: 'RE', text: 'Runtime Error' },
        { value: 'CE', text: 'Compile Error' },
        { value: 'PE', text: 'Presentation Error' },
        { value: 'OLE', text: 'Output Limit Exceeded' },
      ],
    };
  },
  computed: {
    filteredHistory() {
      let filtered = [...this.history];
      if (this.selectedStatus.length > 0) {
        filtered = filtered.filter(item => this.selectedStatus.includes(item.status));
      }
      console.log(filtered);
      return this.sortOrder === 'asc'
        ? filtered.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
        : filtered.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    },
  },
  methods: {
    async fetchHistory() {
      try {
        const response = await axios.get('/api/recommendation_history/recommendation_history/');
        this.history = response.data;
      } catch (error) {
        console.error('无法获取历史记录:', error);
      }
    },
    applyFilters() {
      // This method will re-compute `filteredHistory`
    },
    handleWheel(event) {
      event.preventDefault(); // 阻止默认的滚动行为

      const options = event.currentTarget.options;
      const currentIndex = event.currentTarget.selectedIndex;

      if (event.deltaY > 0) {
        if (currentIndex < options.length - 1) {
          options.selectedIndex += 1; 
        }
      } else {

        if (currentIndex > 0) {
          options.selectedIndex -= 1;
        }
      }
    },
    handleClick(event) {
      this.selectedStatus = event.target.value.split(',');
      if (this.selectedStatus[0] !== this.historyStatus[0]) {
        this.historyStatus = this.selectedStatus;
      } else {
        this.selectedStatus = [];
        this.historyStatus = [];
      }
      console.log(this.selectedStatus);
      console.log(this.historyStatus);
    },
    getProblemLink(problemNumber) {
      return `https://www.luogu.com.cn/problem/${problemNumber}`;
    },
    formatTimestamp(timestamp) {
      return new Date(timestamp).toLocaleString();
    },
    handleMouseEnter(index) { // (5) 修改方法以接受索引参数
      this.hoveredIndex = index; // (6) 更新 hoveredIndex
    },
    hideTooltip() {
      this.hoveredIndex = null; // (7) 更新 hoveredIndex
    }
  },

  mounted() {
    this.fetchHistory();

    const selectElement = document.getElementById('statusSelect');
    
    selectElement.addEventListener('wheel', this.handleWheel);
  },
  beforeUnmount() {
    const selectElement = document.getElementById('statusSelect');
    
    selectElement.removeEventListener('wheel', this.handleWheel);
  },
};
</script>

<style scoped>
.history-page {
  max-width: 90%;
  margin: 20px auto;
}

.filters {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

label {
  font-size: 1.1rem;
  color: #333;
}

select {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.2s ease;
}

select:focus {
  border-color: #007bff;
  outline: none;
}

/* 多选框样式 */
select[multiple] {
  height: auto;
  max-height: 50px;
}

option {
  padding: 10px;
}

select:hover {
  border-color: #007bff;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 10px;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f0f0f0;
}

td a {
  color: #007bff;
  text-decoration: none;
}

.problem-tooltip {
  position: absolute;
  background-color: #ffffff;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 1;
  margin-top: 5px;
  width: 200px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  background-color: #007bff;
  color: white;
  padding: 2px 5px;
  border-radius: 4px;
}
</style>
